package com.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;

/**
 * @author Devin
 * @program my-java
 * @description 时间戳、日期相关处理
 * @date 2024-04-11 11:06
 **/
public class TimeUtil {


    public static int dateToInt(String time){
        // 判断活动结束时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        int timestamp = 0;
        try {
            timestamp = (int) (sdf.parse(time).getTime() / 1000L);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (timestamp == 0 || getNowTimeInt() > timestamp) {
            return 0;
        }
        return timestamp;
    }

    /***
     * 拿到当前的一个int时间
     */
    public static int getNowTimeInt() {
        return (int) (System.currentTimeMillis() / 1000);
    }

    public static long daysBetween(long timestamp) {
        // 将秒级时间戳转换为 LocalDate
        LocalDate dateFromTimestamp = Instant.ofEpochSecond(timestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 计算相距的天数
        long daysDifference = ChronoUnit.DAYS.between(dateFromTimestamp, currentDate);

        // 如果是同一天，返回 1；否则返回实际天数
        return daysDifference == 0 ? 1 : daysDifference;
    }
}
